package com.cdh.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdh.base.DIYException;
import com.cdh.ucenter.entity.Member;
import com.cdh.ucenter.entity.vo.RegisterVo;
import com.cdh.ucenter.mapper.MemberMapper;
import com.cdh.ucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdh.utils.result.ResultCodeEnum;
import com.cdh.utils.util.FormUtil;
import com.cdh.utils.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author cdh
 * @since 2021-03-03
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void register(RegisterVo registerVo) {
        // 校验参数
        String nickname = registerVo.getNickname();
        String password = registerVo.getPassword();
        String phone = registerVo.getPhone();
        String code = registerVo.getCode();

        if (StringUtils.isEmpty(phone) || !FormUtil.isMobile(phone)){
            throw new DIYException(ResultCodeEnum.LOGIN_MOBILE_ERROR.getCode(), ResultCodeEnum.LOGIN_MOBILE_ERROR.getMessage());
        }

        if (StringUtils.isEmpty(nickname)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(code)){
            throw new DIYException(ResultCodeEnum.PARAM_ERROR.getCode(), ResultCodeEnum.PARAM_ERROR.getMessage());
        }

        // 校验验证码
        String verificationCode = (String)redisTemplate.opsForValue().get(phone);
        System.out.println(verificationCode);
        if (!code.equals(verificationCode)){
            throw new DIYException(ResultCodeEnum.CODE_ERROR.getCode(), ResultCodeEnum.CODE_ERROR.getMessage());
        }

        // 校验用户是否存在
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new DIYException(ResultCodeEnum.REGISTER_MOBLE_ERROR.getCode(), ResultCodeEnum.REGISTER_MOBLE_ERROR.getMessage());
        }

        // 注册
        Member member = new Member();
        member.setNickname(nickname);
        member.setMobile(phone);
        member.setPassword(Md5Util.encrypt(password));
        member.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        member.setDeleted(false);
        baseMapper.insert(member);
    }
}
